var router = require('express').Router();
var crypto = require('crypto');
var https = require('https');
var xml2js = require('xml2js');
var connection = require('../lib/utils/DbconnectUtil');
var xmlParser = require('express-xml-bodyparser');
var utils = require('../util/utils');
var WXConfig = require('../config/WXConfig');
var ALiConfig = require('../config/ALiConfig');
var WXService = require('./WXService');
var WXApi = require('../lib/WXApi');
var ALiService = require('../lib/AliPay');
var querystring = require('querystring');

var AliAccount = {
    XIE_HUI: 'cishan_xiehui',
    JI_JIN_HUI: 'cishan_jijinhui'
};


/*
 //TODO 所需参数
 params = {
 //对应捐赠项目ID
 projectId: '000001',
 projectName: '希望工程'
 totalFee: 1,//单位分
 payType: 'WX',//('WX' 'ALi')
 publicFlag: 0,//(公开: 1, 不公开:0)
 userInfo: {
 id: 'xxxxx',
 name: 'frank',
 phoneNumber: '13026655555',
 email: 'xxx@163.com'
 }
 publicFlag: 0,//(公开: 1, 不公开:0)
 }*/
//统一下单地址
router.post('/unifiedOrder', function (req, res, next) {
    //不同支付宝的收款账号,购买的商品信息
    var bodyParams = req.body;

    var params = {
        //对应捐赠项目ID
        projectId: bodyParams.projectId,
        projectName: bodyParams.projectName,
        totalFee: parseFloat(bodyParams.totalFee),//前台传入,单位元
        payType: bodyParams.payType,//('WX' 'ALi')
        selectedAccount: AliAccount.XIE_HUI,
        publicFlag: parseInt(bodyParams.publicFlag),//(公开: 1, 不公开:0)
        userId: bodyParams.userId,
        userName: bodyParams.userName,
        userType: parseInt(bodyParams.userType),
        userPhoneNumber: bodyParams.userPhoneNumber + '',
        userEmail: bodyParams.userEmail,
        userCompany: bodyParams.userCompany,
        postCode: bodyParams.postCode,
        address: bodyParams.address
    };

    //TODO 测试
    // params.totalFee = 0.01;


    var result = {};
    if (!utils.is(params.totalFee, "Number") || params.totalFee <= 0) {
        result.code = -1;
        result.message = "支付金额有误";
        res.send(result);
        return;
    }
    // TODO check params!!!!

    var thirdPayData = {
        out_trade_no: new Date().getTime() + '',
        status: 0,
        subject: params.projectName || '顺义慈善',
        body: params.projectName || '顺义慈善',
        pay_type: params.payType,
        start_time: new Date(),
        total_fee: parseInt(params.totalFee * 100)
    };

    var oderData = {
        id: new Date().getTime() + '',
        status: 0,
        out_trade_no: thirdPayData.out_trade_no,
        project_id: params.projectId,
        project_name: params.projectName,
        user_id: params.userId,
        name: params.userName,
        phone_number: params.userPhoneNumber,
        email: params.userEmail,
        company: params.userCompany,
        user_type: params.userType,
        start_time: new Date(),
        total_fee: parseInt(params.totalFee * 100),
        public_flag: params.publicFlag,
        address: params.address,
        post_code: params.postCode
    };
    // 双向关联
    thirdPayData.attach = oderData.id;

    connection().query('INSERT INTO t_order SET ?', oderData, function (err, result) {
        if (err) {
            res.send({
                code: -1,
                message: 'can not save the order info to db:',
                data: oderData
            });
            return;
        }

        //微信支付
        if (params.payType == 'WX') {
            //TODO 指定trade_type
            var wxOrderParams = {
                body: thirdPayData.body,
                total_fee: thirdPayData.total_fee,
                out_trade_no: thirdPayData.out_trade_no,
                attach: thirdPayData.attach,
                trade_type: 'NATIVE'
            }
            // 创建统一订单
            WXService.unifiedOrder(wxOrderParams, req, function (data, error) {
                if (!data || !data.prepay_id) {
                    res.send(error);
                    return;
                }
                else {
                    connection().query('INSERT INTO t_third_part_pay SET ?', thirdPayData, function (err, result) {
                        if (err) {
                            res.send({
                                code: -1,
                                message: 'can not save the third part pay info to db:',
                                data: thirdPayData
                            });
                            return;
                        }

                        var wxParams = {
                            out_trade_no: thirdPayData.out_trade_no,
                            prepay_id: data.prepay_id,
                            code_url: data.code_url,
                            body: thirdPayData.body,
                            subject: thirdPayData.subject,
                            total_fee: thirdPayData.total_fee
                        };
                        var stringParams = querystring.stringify(wxParams);
                        res.redirect('/#/weixinpay?' + stringParams);
                    });
                }
            });
        }
        //支付宝
        else if (params.payType == 'ALi') {
            var payConfig = ALiConfig[AliAccount.JI_JIN_HUI];
            if (params.selectedAccount == AliAccount.XIE_HUI) {
                payConfig = ALiConfig[AliAccount.XIE_HUI];
            }
            //设置收款账户号
            thirdPayData.account_id = payConfig.seller_id;

            connection().query('INSERT INTO t_third_part_pay SET ?', thirdPayData, function (err, result) {
                if (err) {
                    res.send({
                        code: -1,
                        message: 'can not save the third part pay info to db:',
                        data: thirdPayData
                    });
                    return;
                }

                //根据参数,选择不同的收款账号配置信息
                var payUrl = ALiService.buildDirectPayURL({
                    out_trade_no: thirdPayData.out_trade_no,
                    subject: thirdPayData.subject,
                    body: thirdPayData.body,
                    total_fee: parseFloat(thirdPayData.total_fee) / 100 //转为元(支付宝支付单位为元)
                }, payConfig);

                console.log('payUrl : ' + payUrl);
                res.redirect(payUrl);
            });
        }
    });

});


/*
 {
 "xml":
 {
 "appid": "wx854299a3c0e1b0dd",
 "attach": "attach",
 "bank_type": "CMB_DEBIT",
 "cash_fee": "1",
 "fee_type": "CNY",
 "is_subscribe": "Y",
 "mch_id": "1351290801",
 "nonce_str": "201611071641378824ihbo2kt021brzf",
 "openid": "oRRb_vq3pItrWBRJ2lXWGNaUEHdU",
 "out_trade_no": "20161107164137879000000000520123",
 "result_code": "SUCCESS",
 "return_code": "SUCCESS",
 "sign": "DD7B90848AD8F539986A7907CA7DC11A",
 "time_end": "20161107164205",
 "total_fee": "1",
 "trade_type": "JSAPI",
 "transaction_id": "4002832001201611079028076611"
 }
 }
 */

/* GET notify listing. */
router.post('/wx/notify', xmlParser({trim: true, explicitArray: false}), function (req, res, next) {
    console.log('post req : ' + JSON.stringify(req.body));
    var data = req.body.xml;
    if (data && data.return_code == 'SUCCESS') {
        var thirdPayData = {};
        if (data.total_fee) {
            thirdPayData.total_fee = parseInt(data.total_fee);
        }
        if (data.openid) {
            thirdPayData.user_pay_id = data.openid;
        }
        if (data.appid) {
            thirdPayData.account_id = data.appid;
        }

        thirdPayData.out_trade_no = data.out_trade_no;
        if (data.attach) {
            thirdPayData.attach = data.attach;
        }
        if (data.time_end) {
            var year = parseInt(data.time_end.substr(0, 4));
            var month = parseInt(data.time_end.substr(4, 2)) - 1;
            var day = parseInt(data.time_end.substr(6, 2));
            var hour = parseInt(data.time_end.substr(8, 2));
            var minute = parseInt(data.time_end.substr(10, 2));
            var second = parseInt(data.time_end.substr(12, 2));
            var endDate = new Date(year, month, day, hour, minute, second);
            thirdPayData.end_time = endDate;
        }
        //交易成功
        if (data.result_code == 'SUCCESS') {
            thirdPayData.status = 1;
            thirdPayData.err_msg = '';
        }
        else {
            thirdPayData.status = -1;
            thirdPayData.err_msg = data.err_code_des;
        }

        connection().query('UPDATE t_third_part_pay SET ? where out_trade_no = ?', [thirdPayData, thirdPayData.out_trade_no], function (err, result) {
            console.log('after call db.....');
            if (err) {
                res.send({
                    code: -1,
                    message: 'can not find third part pay when update',
                    data: thirdPayData
                });
                return;
            }

            var orderData = {
                status: thirdPayData.status,
                end_time: thirdPayData.end_time || new Date()
            }

            connection().query('UPDATE t_order SET ? where out_trade_no = ?', [orderData, thirdPayData.out_trade_no], function (err, result) {
                if (err) {
                    console.log('business error, can not update order when pay notify success');
                    return;
                }
                console.log('update order when pay notify success');
                //返回成功请求
                var resXML = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                res.send(resXML);

            });

        });
    }

});


/*
 //只列出必要的几个参数
 notify_time: '2009-08-12 11:08:32'
 out_trade_no:'dddd'
 subject:'deeee',
 trade_status:'',( WAIT_BUYER_PAY
 交易创建，等待买家付款。
 TRADE_CLOSED
 在指定时间段内未支付时关闭的交易；
 在交易完成全额退款成功时关闭的交易。
 TRADE_SUCCESS
 交易成功，且可对该交易做操作，如：多级分润、退款等。
 TRADE_PENDING
 等待卖家收款（买家付款后，如果卖家账号被冻结）。
 TRADE_FINISHED)
 gmt_payment:'2008-10-22 20:49:50'
 seller_id:'111111'
 buyer_id:'2222'
 total_fee:'111'
 body:'eeeee'

 */
/*
 {
 "discount": "0.00",
 "payment_type": "1",
 "subject": "顺义慈善",
 "trade_no": "2016122021001003740204918799",
 "buyer_email": "wang520123fan@163.com",
 "gmt_create": "2016-12-20 20:42:26",
 "notify_type": "trade_status_sync",
 "quantity": "1",
 "out_trade_no": "1482237727729",
 "seller_id": "2088521298902963",
 "notify_time": "2016-12-20 20:42:31",
 "body": "顺义慈善",
 "trade_status": "TRADE_FINISHED",
 "is_total_fee_adjust": "N",
 "total_fee": "0.01",
 "gmt_payment": "2016-12-20 20:42:31",
 "seller_email": "shunyicsjjh@163.com",
 "gmt_close": "2016-12-20 20:42:31",
 "price": "0.01",
 "buyer_id": "2088502996312740",
 "notify_id": "023261e269cabf3bf7c6a6967f17db6lpm",
 "use_coupon": "N",
 "sign_type": "MD5",
 "sign": "67f92d9c7ea539ea088425d55ca268b6"
 }
*/
/*同步通知不要处理业务逻辑,直接写前台地址即可,页面可能被用户关闭,来不及跳转
 * 使用异步notify通知来处理业务*/
router.post('/ali/notify', function (req, res, next) {
    var data = req.body;
    console.log('params : ' + JSON.stringify(data));

    if(!data.out_trade_no){
        console.log('invalid request');
        return ;
    }

    var thirdPayData = {};
    if (data.total_fee) {
        thirdPayData.total_fee = parseInt(data.total_fee * 100);//转化为分为单位
    }
    if (data.buyer_id) {
        thirdPayData.user_pay_id = data.buyer_id;
    }
    if (data.seller_id) {
        thirdPayData.account_id = data.seller_id;
    }

    thirdPayData.out_trade_no = data.out_trade_no;
    if (data.attach) {
        thirdPayData.attach = data.attach;
    }
    if (data.gmt_payment) {
        thirdPayData.end_time = new Date(data.gmt_payment);
    }
    //交易成功
    if (data.trade_status == 'TRADE_FINISHED' || data.trade_status == 'TRADE_SUCCESS') {
        thirdPayData.status = 1;
        thirdPayData.err_msg = '';
    }
    else {
        thirdPayData.status = -1;
        thirdPayData.err_msg = data.error_code;
    }

    connection().query('UPDATE t_third_part_pay SET ? where out_trade_no = ?', [thirdPayData, thirdPayData.out_trade_no], function (err, result) {
        console.log('after call db.....');
        if (err) {
            res.send({
                code: -1,
                message: 'can not find third part pay when update',
                data: thirdPayData
            });
            return;
        }

        var orderData = {
            status: thirdPayData.status,
            end_time: thirdPayData.end_time || new Date()
        }

        connection().query('UPDATE t_order SET ? where out_trade_no = ?', [orderData, thirdPayData.out_trade_no], function (err, result) {
            if (err) {
                console.log('business error, can not update order when pay notify success');
                return;
            }
            console.log('update order when pay notify success');
            //返回成功请求
            res.send('success');
        });
    });

    // 弱化处理,不校验合法性
    /*
     ALiService.verify(params, aliPayConfig, function (err, result) {
     if (err) {
     console.error(err);
     } else {
     if (result === true) {
     console.log('notify success .....');
     // TODO 处理业务逻辑
     res.send('success');
     //该通知是来自支付宝的合法通知
     }
     }
     });*/
});


router.get('/wx/ordersStatus/:outTradeNO', function (req, res, next) {
    connection().query('select * from t_order where out_trade_no = ? ', [req.params.outTradeNO], function (err, result) {
        if (err) {
            res.send({code: -1, message: '服务器内部错误'});
            return;
        }
        if (result && result.length > 0) {
            res.send({code: 0, data: result[0].status});
        }
        else {
            res.send({code: -1, message: '未查询到此订单'});
        }
    });

});

module.exports = router;